<?php

namespace app\common\model\banxi\learn;

use app\common\enums\AccountTypeEnum;
use app\common\model\banxi\organization\Organization as OrganizationModel;
use app\common\model\banxi\student\Student;
use app\common\model\banxi\trainer\Trainer;
use app\common\model\common\BaseModel;
use app\common\service\AccountService;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/**
 * 全科做题记录
 */
class LearnSayReviewRecord extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_learn_say_review_record';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'useTimeDate'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getUseTimeDateAttr($value, $data)
    {
        $value = $value ?: ($data['useTime'] ?? '');
        return secondToTime($value);
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function getListPage($where, $page = "1", $limit = 10)
    {
        return $this->where($where)
            ->order(['id' => 'desc'])
            ->field('id,answerStartTime,rightNum,errorNum,useTime')
            ->paginate([
                'page' => $page,
                'list_rows' => $limit
            ]);
    }

    public function getReviewRecordReport($reviewRecordId, $accountType)
    {
        $reviewRecord = $this->where(['id' => $reviewRecordId])
            ->field('id,studentId,trainerId,useTime,rightNum,errorNum')
            ->find()->toArray();
        if (empty($reviewRecord)) {
            throw new ValidateException('复习记录不存在');
        }

        $accountId = $accountType == AccountTypeEnum::STUDENT ? $reviewRecord['studentId'] : $reviewRecord['trainerId'];
        $accountService = new AccountService();
        $accountInfo = $accountService->getAccountInfo($accountId, $accountType);
        if ($accountInfo && in_array($accountType, [AccountTypeEnum::STUDENT, AccountTypeEnum::TRAINER])) {
            $organizationModel = new OrganizationModel();
            if ($accountInfo['organizationId'] == 0) {
                $accountInfo['organizationInfo'] = $organizationModel->getOrganizationInfo();
            } else {
                $accountInfo['organizationInfo'] = $organizationModel->where('id', $accountInfo['organizationId'])->field('id,name,managerName')->find();
            }
        }
        if ($accountType == AccountTypeEnum::STUDENT) {
            $reviewRecord['student'] = $accountInfo->toArray();
        } else {
            $reviewRecord['trainer'] = $accountInfo->toArray();
        }
        $LearnSayReviewSentenceRecordModel = new LearnSayReviewSentenceRecord();
        $list = $LearnSayReviewSentenceRecordModel->where(['recordId' => $reviewRecord['id']])->field('id,parentTeachSentenceId,sentenceEn,sentenceZh,sentenceAudio,sentenceWordColor,isCorrect')->select()->toArray();
        return [
            'reviewRecord' => $reviewRecord,
            'list' => $list
        ];
    }

    public function getReviewRecordStatistics($skRecordId)
    {
        $list = $this->where(['skRecordId' => $skRecordId, 'isSubmit' => 1])->select()->toArray();
        $totalNum = 0;
        $correctNum = 0;
        foreach ($list as $item) {
            $totalNum += $item['totalNum'];
            $correctNum += $item['errorNum'];
        }
        $correctRate = $totalNum > 0 ? intval($correctNum * 100 / $totalNum) : 0;
        return [
            'totalNum' => $totalNum,
            'correctNum' => $correctNum,
            'correctRate' => $correctRate,
        ];

    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    public function student()
    {
        return $this->hasOne(Student::class, 'id', 'studentId');
    }

    public function trainer()
    {
        return $this->hasOne(Trainer::class, 'id', 'trainerId');
    }

}